package problems.daily;

import utils.beans.ListNode;

/**
 * 1669. 合并两个链表
 * <p>https://leetcode.cn/problems/merge-in-between-linked-lists/</p>
 *
 * @author habitplus
 * @since 10:33, 2023/1/30
 */
public class DT1669 {
    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
        // 指向第 a-1 个节点
        ListNode pre = list1;
        int cnt = b - a + 1;

        while (--a > 0) {
            pre = pre.next;
        }

        ListNode behind = pre.next;
        pre.next = list2;

        while (list2 != null) {
            pre = list2;
            list2 = list2.next;
        }

        while (cnt > 0) {
            list2 = behind.next;
            behind.next = null;
            behind = list2;
            --cnt;
        }

        pre.next = behind;

        return list1;
    }
}
